/**
 * ...
 * @author Rob Dravenstott
 */
import com.chumby.WidgetParams;
import com.chumby.util.Delegate;
class Main 
{
	private static var _widgetParams:WidgetParams = null;
	private static var _appRoot:MovieClip;
	private var _myTed:Ted;
	
	public static function main(swfRoot:MovieClip):Void 
	{
		_appRoot = swfRoot;
		var app = new Main(swfRoot);
	}
	
	public function Main() 
	{
		_quality = "high";

		// Set the scale mode locked so we can resize to stage properly
		Stage.scaleMode = "noScale";
		Stage.align = "TL";
		
		// establish listener functions and retrieves parameters
		_widgetParams = new WidgetParams();
		_widgetParams.addEventListener(WidgetParams.GOT_PARAMS,Delegate.create(_root, gotParameters));
		_widgetParams.addEventListener(WidgetParams.SENT_PARAMS,Delegate.create(_root, sentParameters));
		_widgetParams.getWidgetParams();
	}
	
	private function gotParameters(event:Object) 
	{
		var settings = new Object();

		if (   (event == undefined)
			|| (event == null)
		    || (!event.status))
		{
			trace("Could not load parameters, using defaults.");
		} 	
		else
		{
			//Read the chumby parameters
			var parameters:Object = _widgetParams.chumbyParams();
			
			if (parameters["refresh_time"] != undefined) 
				settings.refresh_time = parameters["refresh_time"];

			if (parameters["ted_address"] != undefined) 
				settings.ted_address = parameters["ted_address"];
		}

		if (_root["_chumby_screen_width"] != undefined)
			settings.max_photo_width = _root["_chumby_screen_width"];
		if (_root["_chumby_screen_height"] != undefined)
			settings.max_photo_width = _root["_chumby_screen_height"];
		
		// Check to make sure we didn't pass in an override via html flashvars appurl param
		if (_level0.refresh_time != undefined)
			settings.refresh_time = _level0.refresh_time;
		if (_level0.ted_address != undefined)
			settings.ted_address = _level0.ted_address;

		//Run the actual presentation code
		_myTed =  new Ted();
		_myTed.run(_appRoot, settings, Main.saveNewSettings);
	}
		
	// Save the data to the server
	public static function saveNewSettings (settings:Object) 
	{
		var parameters:Object = new Object();
				
		parameters["refresh_time"] = String(settings.refresh_time);
		parameters["ted_address"] = String(settings.ted_address);

		if (_widgetParams != null)
		{
			_widgetParams.sendWidgetParams(parameters);
		}
	}

	// called as a callback when done saving the data to the server
	private function sentParameters(event:Object) 
	{
		if (!event.status) 
		{
			trace("Error sending parameters.");
			return;
		}
		else
		{
			trace("Saved");
		}
	}
}